import React, { memo, useState, useEffect } from "react";
import { Button, message } from "antd";
import { getSms } from "services/account";
interface Props {
  username: string;
  module: string;
}

const HYCode = memo((props: Props) => {
  const [disabled, setDisabled] = useState(false);
  const [loading, setLoading] = useState(false);
  const [btnText, setBtnText] = useState("获取验证码");
  const [username, setUsername] = useState("");
  // const [num, setNum] = useState<number>(10);
  let num: number = 10;
  let timer: any;
  // 其它逻辑
  const getCode = (event: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (username === "") {
      return message.warning("请输入用户邮箱！！！");
    }
    if (disabled) return;
    if (timer) {
      clearInterval(timer);
      timer = null;
      return;
    }
    // 发送请求
    handleCode();
    setBtnText("发送中");
    setLoading(true);
    const timers = setInterval(() => {
      num--;
      // setNum(nums);
      setBtnText(num + "s");
      timer = timers;

      if (num < 0) {
        clearInterval(timers);
        timer = null;
        setBtnText("重新获取");
        setLoading(false);
        setDisabled(false);
        num = 10
        return;
      }
    }, 1000);
  };
  const handleCode = async () => {
    const res: any = await getSms({ username, module: props.module });
    const { resCode } = res;
    resCode === 0 ? message.success(res.message) : message.warn(res.message);
  };
  useEffect(() => {
    if (props.username === username) return;
    setUsername(props.username);
  }, [props.username, username]);

  // 生命周期
  useEffect(() => {
    return () => {
      clearInterval(timer);
    };
  }, [timer]);

  return (
    <Button
      htmlType="submit"
      block
      onClick={getCode}
      disabled={disabled}
      loading={loading}
      type="primary"
    >
      {btnText}
    </Button>
  );
});

export default HYCode;
